package parsing;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLWriter {
	File f;
		private DocumentBuilderFactory docFactory;
		private DocumentBuilder docBuilder;
		private Document doc;
		private Element element;
		private Element rootElement;
		private TransformerFactory transformerFactory;
		private Transformer transformer;
		private DOMSource source;
		private StreamResult result;
		
	public XMLWriter() throws ParserConfigurationException, TransformerConfigurationException {
		f = new File("slide.xml");
		docFactory = DocumentBuilderFactory.newInstance();
		docBuilder = docFactory.newDocumentBuilder();
		doc = docBuilder.newDocument();
		transformerFactory = TransformerFactory.newInstance();
		transformer = transformerFactory.newTransformer();
		source = new DOMSource(doc);
		rootElement = doc.createElement("slide");
	}
	
	//method voor elementen zonder waarden
	public void addElement(String elementName) throws TransformerException{
		element = doc.createElement(elementName);
		rootElement.appendChild(element);
	}
	
	//overload voor elementen met waarden
	public void addElement(String elementName, String elementValue) throws TransformerException{
		element = doc.createElement(elementName);
		element.appendChild(doc.createTextNode(elementValue));
		rootElement.appendChild(element);
	}
	
	//method voor elementen -zonder waarden- met attributen
	public void addElementWithAttribute(String elementName, String[] attr){
		element = doc.createElement(elementName);
		writeAttributes(attr);
		rootElement.appendChild(element);
	}
	
	public void addElementWithAttribute(String elementName, String[] attr, String elementValue){
		element = doc.createElement(elementName);
		writeAttributes(attr);
		element.appendChild(doc.createTextNode(elementValue));
		
		rootElement.appendChild(element);
	}
	
	public void commit() throws TransformerException
	{
		doc.appendChild(rootElement);
		transformerFactory = TransformerFactory.newInstance();
		transformer = transformerFactory.newTransformer();
		source = new DOMSource(doc);
		result = new StreamResult(f);
		transformer.transform(source, result);
		System.out.println("end");
	}
	
	private void writeAttributes(String[] attr){
		String attrName = "", attrValue = "";
		for(int i = 0;i<=attr.length-1;i++){
			if(i % 2 == 0 || i == 0){
				attrName = attr[i];
			}else{
				attrValue = attr[i];
			}
			element.setAttribute(attrName,attrValue);
		}
	}
}
